package org.goat.caprabank.client;

import org.goat.caprabank.shared.entity.User;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class RegistrationPanel extends Composite {
	interface RegistrationPanelUiBinder extends UiBinder<Widget, RegistrationPanel> {
	}
	private static RegistrationPanelUiBinder uiBinder = GWT.create(RegistrationPanelUiBinder.class);

	private final Caprabank caprabank;

	public RegistrationPanel(Caprabank caprabank) {
		initWidget(uiBinder.createAndBindUi(this));
		this.caprabank = caprabank;
	}

	@UiField
	TextBox firstNameTextBox;

	@UiField
	TextBox lastNameTextBox;

	@UiField
	TextBox emailTextBox;

	@UiField
	TextBox usernameTextBox;

	@UiField
	PasswordTextBox passwordTextBox;

	@UiField
	PasswordTextBox retypePasswordTextBox;

	@UiHandler("registerButton")
	void onClickRegister(ClickEvent e) {
		boolean isValid = Validation.validateNotNull(firstNameTextBox, "first name") && Validation.validateNotNull(lastNameTextBox, "last name") && Validation.validateNotNull(emailTextBox, "email")
				&& Validation.validateNotNull(passwordTextBox, "password") && Validation.validateNotNull(retypePasswordTextBox, "retype password");
		if (isValid && !passwordTextBox.getText().equals(retypePasswordTextBox.getText())) {
			isValid = false;
			new ErrorDialog().showMessage("The password fields do not match.");
		}
		if (isValid) {
			caprabank.bankService.register(firstNameTextBox.getText(), lastNameTextBox.getText(), emailTextBox.getText(), usernameTextBox.getText(), passwordTextBox.getText(), new DefaultCallback<User>() {

				@Override
				public void onSuccess(User result) {
					caprabank.showAccountDetailsPage(result);
				}
			});
		}
	}

	@UiHandler("cancelButton")
	void onClickCancel(ClickEvent e) {
		caprabank.showLoginPage();
	}
}
